﻿@using XRM.Security.DataAccess.Enums
@using XRM.Security.WebUI.Enums
@using XRM.Security.WebUI.Models.Request
@using XRM.Security.WebUI.MvcHelpers
@model XRM.Security.WebUI.Models.Request.RequestModel
@{
    ViewBag.Title = Model.IsEdit ? "Заявка №" + Model.Number : "Создание заявки";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (Model.RedirectToUserPage)
{
    @Html.Partial("ReturnLinkPartial", new Tuple<string, string>(Url.Action("Edit", "UserRegister", new { id = Model.UserRegisterId }), ""))
}
else
{
    @Html.Partial("ReturnLinkPartial", new Tuple<string, string>(Url.Action("Index"), "Вернуться к списку заявок"))
}

@{
    bool closeRequest = false;
    bool closeWorkKind = false;
    if (TempData["CloseRequest"] != null)
    {
        closeRequest = true;
        TempData["CloseRequest"] = null;
    }
    else if (TempData["CloseWorkKind"] != null)
    {
        closeWorkKind = true;
        TempData["CloseWorkKind"] = null;
    }

    var workKindCount = (Model.WorkKindList != null && Model.WorkKindList.Any() ? Model.WorkKindList.Count(x => x.WorkKind.Id == (int)WorkKindCode.ScsiNewUser || x.WorkKind.Id == (int)WorkKindCode.ScsiNewPC) : 0);

}
<div>
    @using (Html.BeginForm("Edit", "Request", FormMethod.Post, new { @class = "form-horizontal form-horizontal-2", id = "formRequestEdit" }))
    {
        @Html.AntiForgeryToken()

        const string inputCss = "form-control";
        const string divCss = "col-sm-4";

        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.Number)
        @Html.HiddenFor(m => m.UserRegisterId)
        @Html.HiddenFor(m => m.UserRegisterName)
        @Html.HiddenFor(m => m.CreateDate)
        @Html.HiddenFor(m => m.Status)
        @Html.HiddenFor(m => m.RedirectToUserPage)
        @Html.HiddenFor(m => m.SubmitAction)
        @Html.HiddenFor(m => m.WorkKindIdClose)

        @Html.DialogFormButton(new DialogButtonOptions()
   {
       Text = "Выбрать пользователя",
       ContentUrl = Url.Action("ADUsersDialog", "UserRegister"),
       Width = "800",
       Id = "dlgADUsersDialog",
       ButtonCss = "btn btn-large btn-primary hidden",
       OnSuccess = "GetSelectedUser",
       ButtonId = "btnSelectUser",
       OnOpen = "InitSearchUsersDialog"
   })

        if (Model.IsEdit)
        {
            <div class="form-group">
                @Html.LabelFor(m => m.CreateDate, new { @class = "control-label" })
                <div class="@divCss control-text">
                    @Model.CreateDate.ToString("dd.MM.yyyy HH:mm")
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Status, new { @class = "control-label" })
                <div class="@divCss control-text">
                    @Model.StatusCaption
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.DeadLine, new { @class = "control-label" })
                <div class="@divCss">
                    @Html.EditorFor(m => m.DeadLine)
                    @Html.ValidationMessageFor(m => m.DeadLine)
                </div>
            </div>

            if (Model.Status == RequestStatus.Closed)
            {
                <div class="form-group">
                    @Html.LabelFor(m => m.CloseDate, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.TextBox("tbCloseDate", Model.CloseDate.Value.ToString("dd.MM.yyyy"), new { @class = @inputCss, disabled = "disabled" })
                    </div>
                </div>
            }
            <div class="form-group">
                @Html.LabelFor(m => m.SystemUserId, new { @class = "control-label required" })
                <div class="@divCss">
                    @if (Model.Status == RequestStatus.Closed)
                    {
                        @Html.DropDownListFor(m => m.SystemUserId, Model.SystemUserAllList, new { @class = @inputCss })
                    }
                    else
                    {
                        @Html.DropDownListFor(m => m.SystemUserId, Model.SystemUserNotDeletedList, new { @class = @inputCss })
                    }
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.UserRegisterId, new { @class = "control-label required" })
                <div class="@divCss">
                    <div class="input-group">
                        @Html.TextBox("tbUserFullName", Model.UserRegisterName, new { @class = @inputCss })
                        <span class="input-group-btn">
                            <button id="btnSearch" class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
                        </span>
                    </div>
                    @Html.ValidationMessageFor(m => m.UserRegisterId)
                </div>
            </div>

        }
        else
        {
            <div class="form-group">
                @Html.LabelFor(m => m.UserRegisterId, new { @class = "control-label required" })
                <div class="@divCss">
                    <div class="input-group">
                        @Html.TextBox("tbUserFullName", Model.UserRegisterName, new { @class = @inputCss })
                        <span class="input-group-btn">
                            <button id="btnSearch" class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
                        </span>
                    </div>
                    @Html.ValidationMessageFor(m => m.UserRegisterId)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.SystemUserId, new { @class = "control-label required" })
                <div class="@divCss">
                    @Html.DropDownListFor(m => m.SystemUserId, Model.SystemUserNotDeletedList, new { @class = @inputCss })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.DeadLine, new { @class = "control-label" })
                <div class="@divCss">
                    @Html.EditorFor(m => m.DeadLine)
                    @Html.ValidationMessageFor(m => m.DeadLine)
                </div>
            </div>
        }
        <div class="form-group">
            @Html.LabelFor(m => m.WorkKindList, new { @class = "control-label required" })
            <div class="@divCss" id="workkindArray">
                <div data-bind="template: { name: 'workkind-template', foreach: WorkKind }"></div>
                @if (!Model.ReadOnly)
                {
                    <div class="control-text">
                        <a href="#" data-bind="click: addWorkKind" id="lnkAddWorkKind">Добавить вид работ</a>
                    </div>
                }
                @Html.ValidationMessageFor(m => m.WorkKindList)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.Comment, new { @class = "control-label" })
            <div class="@divCss">
                @Html.TextAreaFor(m => m.Comment, 5, 1, new { @class = @inputCss })
            </div>
        </div>

        if (!Model.ReadOnly)
        {
            <div class="form-group">
                <div class="actions">
                    <button class="btn btn-primary" type="button" id="btnSave" onclick="SubmitForm('save', '-1')">Сохранить</button>
                    <button class="btn btn-default" type="button" onclick="goBack();" id="btnCancel">Отмена</button>
                </div>
            </div>
        }

        if (Model.IsEdit)
        {
            <div class="form-group">
                <div class="actions">

                    @if (!Model.ReadOnly)
                    {
                        <button class="btn btn-default" type="button" onclick="SubmitForm('closeRequest', '-1')">
                            <span aria-hidden="true" class="fa fa-action fa-check"></span><br />
                            Закрыть заявку
                        </button>

                        @Html.DialogFormButton(new DialogButtonOptions()
                        {
                        Text = "Закрыть заявку",
                        ContentUrl = Url.Action("CloseDialog", "Request", new { requestId = Model.Id }),
                        Width = "400",
                        Id = "dlgCloseRequestDialogDialog",
                        ButtonCss = "btn btn-default hidden",
                        ImageButton = "fa-check",
                        OnSuccess = "RefreshPage",
                        ButtonId = "btnCloseRequestDialog"
                        })

                        if (Model.Status == RequestStatus.InWork)
                        {
                        @Html.DialogFormButton(new DialogButtonOptions()
                        {
                        Text = "Отметить как ошибочную",
                        ContentUrl = Url.Action("CancelDialog", "Request", new { requestId = Model.Id }),
                        Width = "400",
                        Id = "dlgCancelRequestDialogDialog",
                        ButtonCss = "btn btn-default",
                        ImageButton = "fa-times",
                        OnSuccess = "RefreshPage"
                        })
                        }
                    }

                    <span id="printActions">
                        <button class="dialogLink btn btn-default" type="button"
                                onclick="javascript:{window.location.href = '@Url.Action("PrintRequest", new { requestId = Model.Id, type = PrintFormType.PrintRequest })';}">
                            <span aria-hidden="true" class="fa fa-action fa-print"></span><br>Печать заявки
                        </button>

                        @if (workKindCount > 1)
                        {
                            @Html.DialogFormButton(new DialogButtonOptions()
                        {
                            Text = "Акт установки СКЗИ",
                            ContentUrl = Url.Action("SelectWorkKind", "Request", new { requestId = Model.Id, type = PrintFormType.ActSettingSCSI }),
                            Width = "600",
                            Id = "dlgSelectWorkKindDialogDialog",
                            ButtonCss = "btn btn-default",
                            ImageButton = "fa-print",
                            OnSuccess = "RefreshPage"
                        })

                            @Html.DialogFormButton(new DialogButtonOptions()
                        {
                            Text = "Акт внедрения СКЗИ",
                            ContentUrl = Url.Action("SelectWorkKind", "Request", new { requestId = Model.Id, type = PrintFormType.ActIntroducingSCSI }),
                            Width = "600",
                            Id = "dlgSelectWorkKindDialogDialog",
                            ButtonCss = "btn btn-default",
                            ImageButton = "fa-print",
                            OnSuccess = "RefreshPage"
                        })
                        }
                        else if (workKindCount == 1)
                        {
                            <button class="dialogLink btn btn-default" type="button"
                                    onclick="javascript:{window.location.href = '@Url.Action("PrintRequest", new { requestId = Model.Id, type = PrintFormType.ActSettingSCSI, requestWorkKindId = Model.WorkKindList.FirstOrDefault().Id })';}">
                                <span aria-hidden="true" class="fa fa-action fa-print"></span><br>Акт установки СКЗИ
                            </button>

                            <button class="dialogLink btn btn-default" type="button"
                                    onclick="javascript:{window.location.href = '@Url.Action("PrintRequest", new { requestId = Model.Id, type = PrintFormType.ActIntroducingSCSI, requestWorkKindId = Model.WorkKindList.FirstOrDefault().Id })';}">
                                <span aria-hidden="true" class="fa fa-action fa-print"></span><br>Акт внедрения СКЗИ
                            </button>
                        }
                    </span>
                </div>
            </div>
        }
    }

</div>

<script type="text/html" id="workkind-template">
    <div class="input-list-item" data-bind="css: { 'input-group': $index() >= 0 }, attr: { id: divId }">
        <input type="hidden" data-bind="attr: { name: 'WorkKindList[' + $index() + '].Id', id: divId + '_hidden_id' }, value: id" />
        <input type="hidden" data-bind="attr: { name: 'WorkKindList[' + $index() + '].WorkKindId', id: divId + '_hidden_workkind_id' }" />
        <select class="form-control" data-bind="attr: { name: 'WorkKindList[' + $index() + '].ddl' }, options: WorkKindAll, optionsText: 'name', optionsValue: 'id', value: selectedValue, disable: (disabled == 1)" />
        <span class="input-group-btn" data-bind="">
            <button title="Удалить вид работ" class="btn btn-default" type="button" data-bind="click: $parent.removeWorkKind, disable: (disabled == 1)">
                <i class="fa fa-times"></i>
            </button>
        </span>
    </div>
    <div data-bind="attr: { id: divId + '_sub' }"></div>
</script>

@section scripts
{
    @Scripts.Render("~/bundles/gridlibrary")
    <script type="text/javascript" src="@(Url.Content("~/Scripts/AjaxRequest.js"))"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            PrepareUserRegisterEdit();
            UserEnabled();
            @if (Model.ReadOnly)
            {
                <text>
                    ReadOnlyView();
                    $("#printActions :input").prop("disabled", false);
                </text>
            }

            @if (closeRequest)
            {
                <text>$("#btnCloseRequestDialog").trigger("click");</text>
            }
        });

        function UserEnabled() {
            if ($("#UserRegisterId").val() > 0) {
                $("#lnkAddWorkKind").removeClass('disabled');
                //$("#lnkAddWorkKind").show();
            }
            else {
                $("#lnkAddWorkKind").addClass('disabled');
                //$("#lnkAddWorkKind").hide();
            }

            if (koModel.WorkKind().length > 0) {
                $("#tbUserFullName").prop('disabled', true);
                $("#btnSearch").prop('disabled', true);
            }
            else {
                $("#tbUserFullName").prop('disabled', false);
                $("#btnSearch").prop('disabled', false);
            }
        }

        function SetUserRegister(id, name) {
            $("#UserRegisterId").val(id);
            $("#tbUserFullName").val(name);
            $("#UserRegisterName").val(name);
            UserEnabled();
        }

        function SubmitForm(submitAction, workKindIdClose) {
            $("#SubmitAction").val(submitAction);
            $("#WorkKindIdClose").val(workKindIdClose);
            $("#formRequestEdit").submit();
        }

    </script>
    <script src="@Url.Content("~/Scripts/knockout-3.2.0.js")"></script>
    <script type="text/javascript">

        function RequestViewModel() {
            var self = this;

            self.WorkKindAll = ko.observableArray([
                @{
                    if ((Model.WorkKindAllList != null) && (Model.WorkKindAllList.Any()))
                    {
                        foreach (var item in Model.WorkKindAllList)
                        {
                            <text>{ id: '@item.Id', name: '@item.Name.Replace("\\", "\\\\")' },</text>
                        }
                    }
                    else
                    {
                        <text>{ id: '-1', name: '' }</text>
                    }
                }
            ]);

            self.WorkKind = ko.observableArray([
                @{
                    if ((Model.WorkKindList != null) && (Model.WorkKindList.Any()))
                    {
                        for (int i = 0; i < Model.WorkKindList.Count; ++i)
                        {
                            var item = Model.WorkKindList[i];
                            <text>{ id: '@item.Id', WorkKindAll: self.WorkKindAll, selectedValue: '@item.WorkKind.Id', divId: 'divWorkKind' + '@i.ToString()', disabled: '@(item.CloseDate.HasValue ? "1" : "0")' },</text>
                        }
                    }
                }
            ]);

            self.addWorkKind = function () {
                self.WorkKind.push({ id: "-1", WorkKindAll: self.WorkKindAll, selectedValue: '-1', divId: 'divWorkKind' + String(self.WorkKind().length), disabled: '0' });
                BindWorkKind();
                UserEnabled();
            };

            self.removeWorkKind = function () {
                self.WorkKind.remove(this);
                UserEnabled();
            };
        }

        koModel = new RequestViewModel();
        ko.applyBindings(koModel, document.getElementById("workkindArray"));
        window.setTimeout(function () {
            BindWorkKind();
            countDdl = $("select[name^='WorkKindList']").length;
            $("select[name^='WorkKindList']").trigger("change");
        }, 100);
        //BindWorkKind();
        //countDdl = $("select[name^='WorkKindList']").length;
        //$("select[name^='WorkKindList']").trigger("change");

        function BindWorkKind() {
            $("select[name^='WorkKindList']").change(function () {
                var baseUrl = '@Url.Action("GetWorkKindParamView")';
                var parentId = this.parentElement.id;
                var workKindId = this.value;
                $('#' + parentId + '_hidden_workkind_id').val(this.value);
                var id = $('#' + parentId + '_hidden_id').val();
                var uId = $('#UserRegisterId').val();
                baseUrl += '?id=' + id + '&uId=' + uId + '&wkId=' + workKindId + '&contId=' + parentId;
                $('#' + parentId + '_sub').load(baseUrl, function () {
                    if (countDdl > 0) {
                        --countDdl;
                        if (countDdl == 0)
                            AfterControlsLoad();
                    }
                });
            });
        }

        function AfterControlsLoad() {
            @if (closeWorkKind)
            {
                <text>$("#CloseWorkKind@(Model.WorkKindIdClose.ToString())").trigger("click");</text>
            }
        }

        function RefreshPage() {
            window.location = window.location;
        }
        
        function RefreshRequestParam(index) {
            window.setTimeout(function () {
                $("select[name='WorkKindList[" + index + "].ddl'").trigger("change");
            }, 100);

            //$("select[name='WorkKindList[" + index + "].ddl'").trigger("change");
        }

        function DeleteRequestCert(id, index) {
            if (confirm('Вы действительно хотите удалить сертификат ?')) {

                $.ajax({
                    async: false,
                    cache: false,
                    type: 'POST',
                    url: '@(Url.Action("DeleteRequestCert", "Request"))',
                    data: { id: id },
                    success: function (result) {
                        RefreshRequestParam(index);
                   },
                    error: handleAjaxError
                });

            }
        }

    </script>

}